import { h } from './element';
import { cssPrefix } from '../config';
import Button from './button';
import Icon from './icon';
import { t } from '../locale/locale';
import {reactive} from './reactive'
import helper from '../core/helper'
//数据处理中心
const $reactive = reactive({list:[],style:{}});
const btnClick = function (type) {
  if (type !== 'close') {
    let newDataFilter = helper.cloneDeep(this.dataFilter.list)
    this.data.changeData(()=>{
      this.data.dataFilter = newDataFilter;
    })
    this.change()
  }
  this.isHide = true;
  this.el.hide();
};
const deleteItem = function(index){
    this.dataFilter.list.splice(index,1);
    render.call(this);
  },
  addItem = function(){
    this.dataFilter.list.push({
      table: '',
      code: '',
      value: '',
      op: '==',
      join: 'and'
    })
    render.call(this);
  },
  addListDom = function(){
    let echo = [],{dataFilter} = this;
    if(dataFilter.list.length == 0)return [''];
    dataFilter.list.forEach((item,index)=>{
      echo.push(h('ul',`${cssPrefix}-dataFilter-item`).children(
        ...addItemDom.call(this,item,index)
      ))
    })
    return echo;
  },
  getCodeOptions = function(item,index){
    let dataDb = this.data.dataDb;
    let codeOptions = []
    dataDb.forEach(db=>{
      if(db.value == item.table){
        db.codes.forEach(code=>{
          codeOptions.push(h('option',`${cssPrefix}-dataFilter-option`).attr({
            label: code.label,
            value: code.value
          }))
        })
      }
    })
    return codeOptions.length == 0?['']:codeOptions;
  },
  addItemDom = function(item,index){
    let echo = []
    let btnEl = h('li',`${cssPrefix}-dataFilter-delete`).children(
      new Icon('close').on('click', deleteItem.bind(this,index))
    )
    let tableEl = h('li',`${cssPrefix}-dataFilter-li`).children(
      h('label',`${cssPrefix}-dataFilter-label`).html('数据集：'),
      h('select',`${cssPrefix}-dataFilter-select`).children(
        ...(()=>{
          let echo = [],dataDb = this.data.dataDb;
          dataDb.forEach(db=>{
            echo.push(h('option',`${cssPrefix}-dataFilter-option`).attr({
              label: db.label,
              value: db.value
            }))
          })
          return echo.length == 0?['']:echo;
        })()
      ).attr({placeholder:'请选择数据集',name:'value'})
       .model($reactive,item,'table')
       .on('change',()=>{
          item.code = '';
          codeSelect.html('').children(
            ...getCodeOptions.call(this,item,index)
          );
          codeEl.show();
       })
    );
    let codeSelect;
    let codeEl = h('li',`${cssPrefix}-dataFilter-li`).children(
      h('label',`${cssPrefix}-dataFilter-label`).html('字段：'),
      codeSelect = h('select',`${cssPrefix}-dataFilter-select`)
       .attr({placeholder:'请选择字段',name:'code'})
       .model($reactive,item,'code')
    ).hide();
    let opEl = h('li',`${cssPrefix}-dataFilter-li`).children(
      h('label',`${cssPrefix}-dataFilter-label`).html('操作：'),
      h('select',`${cssPrefix}-dataFilter-select`).children(
        h('option',`${cssPrefix}-dataFilter-option`).attr({
          label: '==',
          value: '=='
        }),
        h('option',`${cssPrefix}-dataFilter-option`).attr({
          label: '!=',
          value: '!='
        }),
        h('option',`${cssPrefix}-dataFilter-option`).attr({
          label: '>',
          value: '>'
        }),
        h('option',`${cssPrefix}-dataFilter-option`).attr({
          label: '>=',
          value: '>='
        }),
        h('option',`${cssPrefix}-dataFilter-option`).attr({
          label: '<',
          value: '<'
        }),
        h('option',`${cssPrefix}-dataFilter-option`).attr({
          label: '<=',
          value: '<='
        }),
        h('option',`${cssPrefix}-dataFilter-option`).attr({
          label: 'in',
          value: 'in'
        }),
        h('option',`${cssPrefix}-dataFilter-option`).attr({
          label: 'like',
          value: 'like'
        })
      ).attr({placeholder:'请选择操作',name:'op'})
       .model($reactive,item,'op')
    );
    let valueEl = h('li',`${cssPrefix}-dataFilter-li`).children(
      h('label',`${cssPrefix}-dataFilter-label`).html('比较值：'),
      h('input',`${cssPrefix}-dataFilter-input`)
      .attr({placeholder:'请输入值'})
      .model($reactive,item,'value')
    )
    let connectEl = h('li',`${cssPrefix}-dataFilter-li`).children(
      h('label',`${cssPrefix}-dataFilter-label`).html('条件：'),
      h('select',`${cssPrefix}-dataFilter-select`).children(
        h('option',`${cssPrefix}-dataFilter-option`).attr({
          label: 'and',
          value: 'and'
        }),
        h('option',`${cssPrefix}-dataFilter-option`).attr({
          label: 'or',
          value: 'or'
        })
      ).attr({placeholder:'请选择字段',name:'value'})
       .model($reactive,item,'join')
    );
    //如果是
    if(item.table){
      codeSelect.html('').children(
        ...getCodeOptions.call(this,item,index)
      )
      window.codeSelect = codeSelect;
      codeEl.show();
    }
    echo.push(btnEl,tableEl,codeEl,opEl,valueEl,connectEl)
    return echo;
  },
  render = function(){
    this.listEl.html('');
    this.listEl.children(...addListDom.call(this))
  };
/**
 * 过滤数据结构
 * [{
 *    table: '',
 *    code: cell | 表名.字段名
 *    value:'""
 *    op: == != > >= < <= in like
 *    join: and or
 * }]
 */
export default class DataFilter{
  constructor(data){
    this.isHide = true;
    this.data = data;
    this.dataFilter = $reactive.proxyData;
    this.el = h('div', `${cssPrefix}-dataFilter`)
      .children(
        h('div',`${cssPrefix}-dataFilter-bar`).children(
          h('div', '-title').child(t('dataFilter.title')),
          h('div', '-right').children(
            h('div', `${cssPrefix}-buttons`).children(
              new Button('close').on('click', btnClick.bind(this, 'close')),
              new Button('ok', 'primary').on('click', btnClick.bind(this, 'ok')),
            ),
          ),
        ),
        h('div',`${cssPrefix}-dataFilter-add`).children(
          new Icon('add').on('click',addItem.bind(this))
        ),
        h('div',`${cssPrefix}-dataFilter-content`).children(
          this.listEl = h('div',`${cssPrefix}-dataFilter-list`)
        )
      ).hide()
  }
  reset(){
    if (this.isHide) return;
    const { data } = this;
    this.dataFilter.list = helper.cloneDeep(data.dataFilter || []);
    render.call(this);
  }
  resetData(data) {
    this.data = data;
    this.reset();
  }
  open(){
    this.isHide = false;
    this.reset();
    this.el.show();
  }
}